package cn.edu.scau.cmi.mingjunhui.composite.consistent;

import java.util.Iterator;
import java.util.Set;

public class ConsistentComposite extends ConsistentComponent{
	public ConsistentComposite(ConsistentComponent org, String _name)
	{
		super(org, _name);
	}
	
	
	@Override
	public ConsistentComponent addChild(ConsistentComponent child) {
		son.add(child);
		return this;
	}

	@Override
	public Set<ConsistentComponent> getChild() {
		return son;
	}

	@Override
	public ConsistentComponent deleteChild(ConsistentComponent child) {
		son.remove(child);
		return this;
	}
	                                                   
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return toString(0);
	}
	
	@Override
	public String toString(int pos) {
		String parentName = getParent() == null ? "None" : getParent().getName();
		String blank = "";
		for (int i=0; i<pos; i++) blank += " ";
		StringBuilder sb = new StringBuilder();
		for (ConsistentComponent s : son) {
			String rString = s.toString(pos+4);
			rString = rString.substring(0, rString.length()-1);
			String string = rString + ",\n";
			sb.append(string);
		}
		if (sb.length()>=2) {
			sb.deleteCharAt(sb.length()-2);
		}
		String rs = blank +"\"" + getName() + "\": {\n" + 
				blank + " \"类型\": \"团队\",\n" +
				blank + " \"父亲\": \"" + parentName + "\",\n" + 
				blank + " \"孩子\": [\n" + 
				sb.toString() + 
				blank + " ]\n" + 
				blank + "}\n";
		return rs;
	}
	
	@Override
	public ConsistentComponent get(String tarName) {
		// TODO Auto-generated method stub
		
		if(this.name.equals(tarName)) {
			//System.out.println(tarName + this.name);
			return this;
		}
		Iterator<ConsistentComponent> iterator = son.iterator();
		ConsistentComponent target = null;
		while(iterator.hasNext())  {
			ConsistentComponent now = iterator.next().get(tarName);
			if(now!=null) target = now;
		}
		return target;
	}
	
	@Override
	public void setParent(ConsistentComponent p)
	{
		this.parent = p;
	}

}
